//为什么需要redux？
// JavaScript需要管理的状态越来越多，越来越复杂
//这些状态包括服务器返回的数据，缓存数据，用户操作产生的数据等，也包括一些UI的状态
//比如某些元素是否被选中，是否显示加载动效，当前分页
const redux = require('redux');

const initialState = {
  counter: 0,
};

//reducer
function reducer(state = initialState, action) {
  switch (action.type) {
    case 'INCREMENT':
      return { ...state, counter: state.counter + 1 };
    case 'DECREMENT':
      return { ...state, counter: state.counter - 1 };
    case 'ADD_NUMBER':
      return { ...state, counter: state.counter - action.num };
    case 'SUB_NUMBER':
      return { ...state, counter: state.counter - action.num };
    default:
      return state;
  }
}

//store
const stroe = redux.createStore(reducer);

//订阅store的修改
stroe.subscribe(() => {
  console.log('counter:', stroe.getState().counter);
});

//actions
const action1 = { type: 'INCREMENT' };
const action2 = { type: 'DECREMENT' };
const action3 = { type: 'ADD_NUMBER', num: 5 };
const action4 = { type: 'SUB_NUMBER', num: 12 };

//派发action
stroe.dispatch(action1);
stroe.dispatch(action2);
stroe.dispatch(action2);
stroe.dispatch(action3);
stroe.dispatch(action4);
